package com.bian.myRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author bianpengfei
 * @create 2019-02-14 16:35
 **/
@Slf4j
public class MySelfRuleCon extends AbstractLoadBalancerRule {

	private int total = 0; // 总共被调用的次数，目前要求每台被调用5次
	private int currentIndex = 0; // 当前提供服务的机器号
	private int change = 1; // 当前提供服务的机器号

	/**
	 * Randomly choose from all living servers
	 */
	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			// 所有的可访问机器
			List<Server> upList = lb.getReachableServers();
			// 所有的机器(包含挂掉，但未在注册中心删除的)
			List<Server> allList = lb.getAllServers();
			int serverCount = allList.size();
			if (serverCount == 0) {
				log.error("没有可提供服务的机器>>>>>No servers. End regardless of pass, because subsequent passes");
				return null;
			}

			if (total < change) {
				server = upList.get(currentIndex);
				total++;
			} else {
				total = 0;
				currentIndex++;
				if (currentIndex >= upList.size()) {
					currentIndex = 0;
				}
			}
			if (server == null) {
				// 让出时间，防止没服务的时候卡线程
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				log.info(" allList = " + allList.size() + " 		 upList = " + upList.size() + "  	"
						+ server.toString());
				return (server);
			} else {
				server = null;
			}
			// 让出时间，防止服务挂掉的时候卡线程
			Thread.yield();
		}

		return server;

	}

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub

	}
}
